package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private CacheClient cacheClient;


    /**
     * 根据id查询商铺信息
     *
     * @param id
     * @return
     */
    @Override
    public Result queryById(Long id) {
        //解决缓存穿透问题
        //Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY,id,Shop.class,this::getById,CACHE_SHOP_TTL,TimeUnit.MINUTES);
        //互斥锁解决缓存击穿
        //Shop shop = cacheClient.queryWithMutex(CACHE_SHOP_KEY,id,Shop.class,this::getById,CACHE_SHOP_TTL,TimeUnit.MINUTES);
        //逻辑过期解决缓存击穿
        Shop shop = cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //8.将数据返回
        if (shop == null) {
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }

    //缓存数据到redis
    public void saveShop2Redis(Long id, Long expireSeconds) {
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //1.查询店铺数据
        Shop shop = getById(id);
        //2.封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //3.写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }

    //获取锁
    private Boolean tryLock(String key) {
        Boolean ifAbsent = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        //不建议直接返回，直接返回可能出现空指针异常
        return BooleanUtil.isTrue(ifAbsent);
    }

    //释放锁
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }

    //互斥锁解决缓存击穿
    public Shop queryWithMutex(Long id) {
        String key = CACHE_SHOP_KEY + id;
        Shop shop = new Shop();
        //1.从redis中查询商铺缓存
        String shopJSON = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(shopJSON)) {
            //2.如果查询结果不为空，那么将数据进行转换然后返回
            shop = JSONUtil.toBean(shopJSON, Shop.class);
            return shop;
        }
        //3.如果店铺查询出来的值是 ""那么说明击中了 空字符串，直接返回错误信息即可
        if (shopJSON != null) {
            return null;
        }
        //4.1实现缓存重建
        //4.2获取互斥锁
        String lockKey = "lock:shop:" + id;
        Boolean tryLock = tryLock(lockKey);
        try {
            if (!tryLock) {
                //4.3获取失败，那么就进行休眠；休眠足够的时间之后，进行递归，直到获取数据或者拿到锁
                Thread.sleep(50);
                return queryWithMutex(id);
            }

            //5.成功拿到锁，根据id查询数据库
            //再次对redis进行检查，查看缓存是否存在;如果缓存里面有那么就直接返回
            shopJSON = stringRedisTemplate.opsForValue().get(key);
            if (StrUtil.isNotBlank(shopJSON)) {
                //5.1如果缓存里面有数据，那么就直接返回数据；并且释放锁
                shop = JSONUtil.toBean(shopJSON, Shop.class);
                unLock(lockKey);
                return shop;
            }
            //6.如果店铺不存在，那么就从数据库里面查询出数据
            shop = getById(id);
            if (shop == null) {
                //6.1店铺不存在，向redis存入空值
                stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                //6.2返回错误信息
                return null;
            }
            //6.3.如果存在，那么就将数据数据缓存到redis里面，返回查询数据；释放锁
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unLock(key);

        }
        return shop;
    }

    public static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    //逻辑过期解决缓存击穿
    public Shop queryWithLogicalExpire(Long id) {
        String key = CACHE_SHOP_KEY + id;
        //1.获取缓存
        String shopJSON = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(shopJSON)) {
            //2.如果字符串为空，那么就返回空值
            return null;
        }
        //3.不为空，先将json反序列化为对象
        RedisData redisData = JSONUtil.toBean(shopJSON, RedisData.class);
        Shop shop = JSONUtil.toBean((String) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();

        //4.判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //5.如果不过期，那么直接返回对象
            return shop;
        }
        //5.1已过期，缓存重建
        //6.缓存重建
        //6.1获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        Boolean islLock = tryLock(lockKey);
        //6.2判断是否获取锁成功
        if (islLock) {
            //6.3成功，开启独立线程，缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    this.saveShop2Redis(id, 20L);
                } catch (Exception e) {
                    throw new RuntimeException();
                } finally {
                    //释放锁
                    unLock(lockKey);
                }
            });
        }
        return shop;
    }

    /**
     * 更新店铺信息
     *
     * @param shop
     * @return
     */
    @Override
    @Transactional
    public Result updateMessage(Shop shop) {
        //1.获取商店的id
        Long id = shop.getId();
        if (id == null) {
            //2.如果id为空，返回错误信息
            return Result.fail("店铺id不能为空");
        }
        String key = CACHE_SHOP_KEY + id;
        //3.更新数据库
        updateById(shop);
        //4.清理缓存
        stringRedisTemplate.delete(key);
        return Result.ok();
    }

    /**
     * 根据分类id查询店铺
     *
     * @param typeId
     * @param current
     * @param x
     * @param y
     * @return
     */
    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //1.查看查询数据是否需要经纬度
        if (x != null || y == null) {
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page);
        }
        //2.需要经纬度
        //2.1整理返回的数据
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        String key = SHOP_GEO_KEY + typeId;
        //3.根据分类id以及经纬度查询出附近5公里的商家
        GeoResults<RedisGeoCommands.GeoLocation<String>> search = stringRedisTemplate.opsForGeo().search(key,
                GeoReference.fromCoordinate(x, y),
                new Distance(5000),
                RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeCoordinates().limit(end));
        //4.如果数据为空，那么就返回空list即可
        if (search == null) {
            return Result.ok(Collections.emptyList());
        }
        //5.整理查询的数据
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> results = search.getContent();
        List<Long> ids = new ArrayList<>(results.size());
        Map<String, Distance> distanceMap = new HashMap<>(results.size());

        results.stream().skip(from).forEach(geoResult -> {
            String idStr = geoResult.getContent().getName();
            ids.add(Long.valueOf(idStr));
            Distance distance = geoResult.getDistance();
            distanceMap.put(idStr, distance);
        });
        //6.根据id进行店铺查询
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        //7.设置距离
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId()).getValue());
        }
        return Result.ok(shops);
    }
}
